<template>
  <div class="page-container">
    <el-form :inline="true" :model="search" size="small">
        <el-form-item label-width="商品名称" prop="spuName" style="margin-right: 15px;">
            <el-input style="height: 26px" v-model="search.spuName" placeholder="请输入商品名称" clearable :suffix-icon="Search" @keydown.enter.prevent="bindSearch" @clear="bindSearch"></el-input>
        </el-form-item>
        <el-form-item label-width="商品分类" prop="catalogIds" style="margin-right: 15px;">
            <el-cascader :options="classify" :show-all-levels="false" v-model="search.catalogIds" clearable
							:props="{value: 'id', label: 'name'}" placeholder="请选择分类" @change="selCatalogId"></el-cascader>
        </el-form-item>
        <el-form-item label-width="商品类型" prop="goodsType" style="margin-right: 15px;">
            <el-select v-model="search.goodsType" placeholder="请选择类型" clearable @change="selGoodsType">
                <el-option v-for="item in goodsTypeOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label-width="上架状态" prop="publishStatus" style="margin-right: 15px;">
            <el-select v-model="search.publishStatus" placeholder="请选择状态" clearable @change="selStatus">
                <el-option v-for="item in publishStatusOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" size="small" @click="addGoods">添加商品</el-button>
            <el-button type="primary" size="small" @click="upBatch(1)" :disabled="multipleSelection.length < 1">批量上架</el-button>
            <el-button type="primary" size="small" @click="upBatch(0)" :disabled="multipleSelection.length < 1">批量下架</el-button>
        </el-form-item>
    </el-form>
    <div class="list-container">
        <el-table :data="list" size="small" @selection-change="handleSelectionChange" @sort-change="sortChange">
            <el-table-column type="selection" width="55" />
            <el-table-column type="expand" v-if="false">
                <template #default="props">
                    <div style="padding: 0 20px">
                        <el-descriptions size="small" :column="4">
                            <el-descriptions-item label="商品名称">{{props.row.spuName}}</el-descriptions-item>
                            <el-descriptions-item label="商品类别">{{ goodsDict[props.row.goodsType]}}</el-descriptions-item>
                            <el-descriptions-item label="商品描述">{{props.row.spuDescription}}</el-descriptions-item>
                            <el-descriptions-item label="所属商店">{{props.row.shop}}</el-descriptions-item>
                        </el-descriptions>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="商品ID" prop="id"></el-table-column>
            <el-table-column label="商品图" prop="thumb" width="80px">
                <template #default="scope">
                    <el-image style="width: 30px; height: 30px" :src="scope.row.image" fit="cover" :preview-src-list="[scope.row.image]" :preview-teleported="true">
                        <template #error>
                            <div class="image-slot">
                                <el-icon><ele-Picture /></el-icon>
                            </div>
                        </template>
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="spuName"></el-table-column>
            <el-table-column label="商品分类" prop="categoryName"></el-table-column>
            <el-table-column label="商品类型" prop="goodsType">
				<template #default="scope">
				    <template v-for= " item,index in goodsTypeOptions" :key="index">
						<el-tag class="spec-tag" size="small"  effect="light" v-if="scope.row.goodsType == item.value"
							>{{item.label}}</el-tag>
					</template>
				</template>
			</el-table-column>
            <el-table-column label="商品售价" prop="price" width="120px" sortable="custom"></el-table-column>
            <el-table-column label="商品销量" prop="sales" width="120px" sortable="custom"></el-table-column>
            <el-table-column label="库存" prop="stock" width="80px" sortable="custom"></el-table-column>            
			<el-table-column label="排序" prop="sort" width="80px"></el-table-column>
            <el-table-column label="状态" prop="publishStatus">
                <template #default="scope">
                    <el-switch size="small" v-model="scope.row.publishStatus" :active-value="1" :inactive-value="0"
                        :active-text="scope.row.publishStatus == 0 ? '下架' : '上架'" @change="changeRow($event, scope.row)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="添加时间" prop="createTime" sortable="custom" ></el-table-column>
            <el-table-column width="200px" label="操作" fixed="right">
                <template #default="scope">
                    <el-button size="small" type="primary" link @click="openDetail(scope.row)">查看</el-button>
                    <el-button size="small" type="primary" link @click="editRow(scope.row)">编辑</el-button>
                    <el-button size="small" type="primary" link @click="delRow(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="page-block">
        <el-pagination
            v-model:currentPage="current"
            v-model:page-size="page"
            :page-sizes="[10, 20, 30, 40]"
            :small="true"
            :disabled="false"
            :background="false"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
    <phone-model v-model:dialogDrawer="dialogPhone" :defaultForm="detail"></phone-model>
  </div>
</template>

<script>
import { toRefs, reactive,onMounted } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import PhoneModel from '../components/PhoneModel.vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {pageList,upShop,remove} from  '/@/api/pms/spu'
import { getCategoryTree,create as createCategory } from '/@/api/pms/category'
import api from '/@/api/commonApi'
export default {
    name: 'ShopList',
    components: {
        PhoneModel
    },
    setup() {
        const router = useRouter()
        const state = reactive({
            search: {
                spuName: '',
				current: 1,
				size: 10,
                isWork: "1", // 工作网
                catalogIds: [],
                goodsType: null,
                publishStatus: null,
                sortName: null,
                countUp: null
            },
            list: [],
            total: 0,
            current: 1,
            page: 10,
            detail: {},
            dialogPhone: false,
            classify: [],
			goodsTypeOptions:[{
				label:'实物商品',
				value:0
			},{
				label:'卡密/网盘',
				value:1
			},{
				label:'付费优惠券',
				value:2
			},{
				label:'虚拟产品/服务',
				value:3
			}],
            publishStatusOptions: [
                { label: '下架', value: 0},
                { label: '上架', value: 1}
            ],
            goodsDict: {
                0: '普通商品',
                1: '卡密/网盘',
                2: '优惠卷',
                3: '虚拟商品'
            },
            multipleSelection:[]
        })
        const bindSearch = () => {
            getList()
        }
        const addGoods = () => {
            router.push({
                path: '/shop/goods-add'
            })
        }
        const changeRow = (e, row) => {
            let ids = []
            ids.push(row.id)
            upGoods(ids,row.publishStatus)
        }
        const openDetail = row => {
            state.detail = row
            state.dialogPhone = true
        }
        const editRow = row => {
            router.push({
                path: '/shop/goods-edit',
                query: {
                    id: row.id
                }
            })
        }
        const delRow = row => {
            ElMessageBox.confirm(
                '是否确认删除名称为"' + row.spuName + '"的数据项？',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                remove(row.id).then(res => {
                    if (res.code == 0) {
                        ElMessage({
                            type: 'success',
                            message: '删除成功',
                        })
                        getList()
                    } else {
                        ElMessage({
                            type: 'error',
                            message: '删除失败：' + res.message,
                        })
                    }
                })
            }).catch()
        }
        const handleSizeChange = e => {
            state.search.size = e
            getList()
        }
        const handleCurrentChange = e => {
            state.search.current = e
            getList()
        }
        const getList = () => {
			api.workList(state.search).then(res=>{
				state.list = res.data.records
				state.total = res.data.total
			})
        }
        const upGoods = (ids,status) => {
			upShop({ids:ids,status:status}).then(res=>{
                if(res.code == 0){
                    ElMessage.success('操作成功')
                    getList()
                }else{
                    ElMessage.error('操作失败') 
                }
            })
        }
        const upBatch = (val) => {
            let ids = []
			for(let m of state.multipleSelection){
                ids.push(m.id)
            }
            upGoods(ids,val)
        }
        const handleSelectionChange = (val) => {
            state.multipleSelection = val
        }
        //获取分类
        const getCategory = () => {
            getCategoryTree({isWork: "1"}).then(res => {
                state.classify = res.data
            })
        }
        // 选择分类        
        const selCatalogId = (val) => {
            state.search.catalogIds = val
            getList()
        }
        // 选择类型
        const selGoodsType = (val) => {
            state.search.goodsType = val
            getList()
        }
        // 选择状态
        const selStatus = (val) => {
            state.search.publishStatus = val
            getList()
        }
        // 获取排序状态
        const sortChange = (val) => {
            if(val.prop == null){
                state.search.sortName = null
                state.search.countUp = null
            }else{
                state.search.sortName = val.prop == 'createTime' ? 'create_time' : val.prop
                state.search.countUp = val.order == 'ascending' ? 'asc' : 'desc'
            }
            getList()
        }

		onMounted(() => {
            getCategory()
		    getList()
		})
        return {
            Plus,
            Search,
            addGoods,
            changeRow,
            openDetail,
            editRow,
            delRow,
            handleSizeChange,
            handleCurrentChange,
            bindSearch,
            upGoods,
            upBatch,
            selStatus,
            sortChange,
            getCategory,
            selCatalogId,
            selGoodsType,
            handleSelectionChange,
            ...toRefs(state)
        }
    }
}
</script>

<style scoped lang="scss">
.list-container{
    background: var(--next-color-white);
    :deep(.el-table__header-wrapper .el-table__cell) {
        background: var(--el-color-primary-light-9);
        color: var(--next-bg-menuBar-light-1);
    }
}
.image-slot{
    display: flex;
    align-items: center;
    justify-content: center;
    height: 30px;
}
</style>